import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import DownloadPage from '../views/DownloadPage.vue'
import { checkLoginStatus } from '../utils/auth'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/download',
    name: 'download',
    component: DownloadPage,
    meta: {
      title: '下载管理'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log(`路由守卫: 从 ${from.path} 跳转到 ${to.path}`)
  
  if (to.meta.requiresAuth) {
    console.log('需要验证登录状态...')
    const isLoggedIn = await checkLoginStatus()
    console.log('登录状态验证结果:', isLoggedIn)
    
    if (isLoggedIn) {
      console.log('登录验证通过，允许访问')
      next()
    } else {
      console.log('登录验证失败，重定向到登录页')
      next('/login')
    }
  } else if (to.path === '/login') {
    console.log('访问登录页，检查是否已登录...')
    // 如果已经登录，直接跳转到dashboard
    const isLoggedIn = await checkLoginStatus()
    console.log('登录页检查结果:', isLoggedIn)
    
    if (isLoggedIn) {
      console.log('已登录，重定向到dashboard')
      next('/dashboard')
    } else {
      console.log('未登录，显示登录页')
      next()
    }
  } else {
    console.log('无需验证，直接通过')
    next()
  }
})

export default router 